<?php

namespace plugins\yifang_backend_account\utils\encrypt;

class Rsa
{

    /**
     * publicDecrypt
     * 公钥加密
     *
     * @param string $data
     * @param string $key
     * @static
     * @return mixed
     */
    public static function publicEncrypt($data,$key,$padding=null)
    {
        $padding=$padding?$padding:OPENSSL_PKCS1_PADDING;
        $data = is_array($data)?json_encode($data):$data;
        if (openssl_public_encrypt($data, $encrypted, $key,$padding)) {
            return base64_encode($encrypted);
        }
        return false;
    }

    /**
     * publicDecrypt
     * 公钥解密
     *
     * @param string $data
     * @param string $key
     * @static
     * @return mixed
     */
    public static function publicDecrypt($data,$key,$padding=null)
    {
        $padding=$padding?$padding:OPENSSL_PKCS1_PADDING;
        $data = base64_decode($data);
        if (openssl_public_decrypt($data, $result, $key,$padding)) {
            return $result;
        }
        return false;
    }

    /**
     * 私钥加密
     *
     * @param  string  $value
     * @param  string  $key
     * @return string
     */
    public static function priviteEncrypt($data,$key,$padding=null){
        $padding=$padding?$padding:OPENSSL_PKCS1_PADDING;
        $data = is_array($data)?json_encode($data):$data;
        if (openssl_private_encrypt($data, $encrypted, $key,$padding)) {
            return base64_encode($encrypted);
        }
        return false;
    }

    /**
     * 私钥解密
     *
     * @param  string  $value
     * @param  string  $key
     * @return string
     */
    public static function priviteDecrypt($data,$key,$padding=null){
        $padding=$padding?$padding:OPENSSL_PKCS1_PADDING;
        $data = base64_decode($data);
        if (openssl_private_decrypt($data, $result, $key,$padding)) {
           return $result;
        }
        return false;
    }

    /**
     * 私钥签名
     *
     * @param  string  $value
     * @param  string  $key
     * @return string
     */
    public static function priviteSign($data,$key,$padding=null){
        $data = is_array($data)?json_encode($data):$data;
        $padding=$padding?$padding:OPENSSL_ALGO_SHA1;
        if (openssl_sign($data, $signature,$key,$padding)) {
            return base64_encode($signature);
        }
        return false;
    }

    /**
     * 公钥签名验证
     *
     * @param  string  $value
     * @param  string  $key
     * @return string
     */
    public static function publicSignVerify($data,$signature,$key,$padding=null){
        $signature=base64_decode($signature);
        $padding=$padding?$padding:OPENSSL_ALGO_SHA1;
        $ok=openssl_verify($data, $signature,$key,$padding);
        if ($ok==1) {
            return true;
        }
        return false;
    }

}


